package course.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import course.constant.ClassStuCount;
import course.pojo.entity.*;
import course.pojo.vo.TeaSubCollegeRespVo;
import course.service.*;
import course.service.impl.*;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author HLF
 * @date 2022/7/3 19:02
 */
@WebServlet("/student/stuTeaController")
public class StudentOrderTeacherController extends BaseController {
    private StuTeaService stuTeaService = new StuTeaServiceImpl();

    private StuSubService stuSubService = new StuSubServiceImpl();

    private TeaSubService teaSubService = new TeaSubServiceImpl();

    private CollegeService collegeService = new CollegeServiceImpl();

    private SubjectService subjectService = new SubjectServiceImpl();

    private TeacherService teacherService = new TeacherServiceImpl();

    /**
     * 跳转到stutea_manage.jsp
     */
    protected void index(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        //获取当前登录的student对象
        Student student = (Student) session.getAttribute("sstudent");
        Integer sid = student.getSid();//学生id

        //1.列出当前学生所有可以选择的教师(当前学生的已选课程中看哪些课程被老师选择教授，找出对应关系)
        List<StuSub> stuSubs = stuSubService.getBySid(sid);
        //筛选出被老师选择的suid，并获得teacher/tid集合
        List<TeaSubCollegeRespVo> collect = new ArrayList<>();
        stuSubs.forEach(stuSub -> {
            Integer suid = stuSub.getSuid();
            Subject subject = subjectService.getById(suid);
            List<TeaSub> teaSubs = teaSubService.getBySuid(suid);
            List<TeaSubCollegeRespVo> respVos = teaSubs.stream().map(teaSub -> {
                TeaSubCollegeRespVo respVo = new TeaSubCollegeRespVo();
                Teacher teacher = teacherService.getById(teaSub.getTid());
                respVo.setCid(teacher.getCid());
                respVo.setCname(collegeService.getById(teacher.getCid()).getCname());
                respVo.setSuid(suid);
                respVo.setSuname(subject.getSuname());
                respVo.setTid(teaSub.getTid());
                respVo.setTname(teacher.getTname());
                return respVo;
            }).collect(Collectors.toList());
            collect.addAll(respVos);
        });

        //2.列出当前学生已经选择的所有教师集合
        List<StuTea> stuTeas = stuTeaService.getBySid(sid);
        List<TeaSubCollegeRespVo> collect2 = stuTeas.stream().map(stuTea -> {
            TeaSubCollegeRespVo respVo = new TeaSubCollegeRespVo();
            try {
                BeanUtils.copyProperties(respVo, stuTea);
                Teacher teacher = teacherService.getById(stuTea.getTid());
                Integer cid = teacher.getCid();
                respVo.setCid(cid);
                respVo.setCname(collegeService.getById(cid).getCname());
                respVo.setTname(teacher.getTname());
                respVo.setSuname(subjectService.getById(stuTea.getSuid()).getSuname());

                return respVo;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }).collect(Collectors.toList());

        req.setAttribute("ownList", collect2);
        req.setAttribute("allList", collect);

        req.getRequestDispatcher("/stutea_manage.jsp").forward(req, resp);
    }

    /**
     * 选择教师
     */
    protected void order(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        //响应给前端的code,msg
        Map<String, Object> result = new HashMap<>();

        String suid = req.getParameter("suid");
        String tid = req.getParameter("tid");

        if (StringUtils.isBlank(suid) || StringUtils.isBlank(tid)) {
            result.put("code", 0);
            result.put("msg", "suid或tid不能为空");
            String stringJson = mapper.writeValueAsString(result);
            writer.println(stringJson);
            return;
        }

        HttpSession session = req.getSession();
        Student student = (Student) session.getAttribute("sstudent");

        List<StuTea> bySidTidSuid = stuTeaService.getBySidTidSuid(student.getSid(), Integer.valueOf(tid), Integer.valueOf(suid));
        if (bySidTidSuid.size() > 0) {
            result.put("code", 0);
            result.put("msg", "不能重复选择同一教师对应的同一课程！");
            String stringJson = mapper.writeValueAsString(result);
            writer.println(stringJson);
            return;
        }

        List<StuTea> bySidSuid = stuTeaService.getBySidSuid(student.getSid(), Integer.valueOf(suid));
        if (bySidSuid.size() > 0) {
            result.put("code", 0);
            result.put("msg", "该课程您已经选择过教师，不能重复选择！");
            String stringJson = mapper.writeValueAsString(result);
            writer.println(stringJson);
            return;
        }

        /**
         * 改进：如果选择的老师所在的班级学生人数超过指定人数，就禁止选择该教师
         */
        List<StuTea> byTidSuid = stuTeaService.getByTidSuid(Integer.valueOf(tid), Integer.valueOf(suid));
        if (byTidSuid.size()>= ClassStuCount.MIDDLE_CLASS){
            result.put("code", 0);
            result.put("msg", "该班级人数已经达到最大限制，不可选择。请尝试选择其他教师！");
            String stringJson = mapper.writeValueAsString(result);
            writer.println(stringJson);
            return;
        }


        StuTea stuTea = new StuTea(student.getSid(), Integer.valueOf(tid), Integer.valueOf(suid));
        int i = stuTeaService.addStuTea(stuTea);
        result.put("code", i);
        if (i > 0) {
            result.put("msg", "选择教师成功！");
        } else {
            result.put("msg", "选择教师失败！");
        }
        String stringJson = mapper.writeValueAsString(result);
        writer.println(stringJson);
    }

    /**
     * 取消选择教师
     */
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        //响应给前端的code,msg
        Map<String, Object> result = new HashMap<>();

        String suid = req.getParameter("suid");
        String tid = req.getParameter("tid");

        if (StringUtils.isBlank(suid) || StringUtils.isBlank(tid)) {
            result.put("code", 0);
            result.put("msg", "suid或tid不能为空");
            String stringJson = mapper.writeValueAsString(result);
            writer.println(stringJson);
            return;
        }

        HttpSession session = req.getSession();
        Student student = (Student) session.getAttribute("sstudent");
        Integer sid = student.getSid();

        int i = stuTeaService.deleteBySidTidSuid(sid, Integer.valueOf(tid), Integer.valueOf(suid));
        result.put("code", i);
        if (i > 0) {
            result.put("msg", "取消选择教师成功！");
        } else {
            result.put("msg", "取消选择教师失败！");
        }
        String stringJson = mapper.writeValueAsString(result);
        writer.println(stringJson);
    }

    /**
     * 批量取消选择(当前student)所有选中的教师
     */
    protected void deleteSelect(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        //响应给前端的code,msg
        Map<String, Object> result = new HashMap<>();

        String[] ids = req.getParameterValues("ids[]");

        if (ids.length == 0) {
            result.put("code", 0);
            result.put("msg", "suid或tid不能为空");
            String stringJson = mapper.writeValueAsString(result);
            writer.println(stringJson);
            return;
        }

        HttpSession session = req.getSession();
        Student student = (Student) session.getAttribute("sstudent");
        Integer sid = student.getSid();

        List<String> list = Arrays.asList(ids);
        list.forEach(s -> {
            int indexOf = s.indexOf(",");
            String suid = s.substring(0, indexOf);
            String tid = s.substring(indexOf + 1);
            int i = stuTeaService.deleteBySidTidSuid(sid, Integer.valueOf(tid), Integer.valueOf(suid));
        });
        result.put("msg", "取消选择所有选中教师成功！");
        String stringJson = mapper.writeValueAsString(result);
        writer.println(stringJson);
    }
}
